﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using BusinessBingo.Model.Interfaces;

namespace BusinessBingo.Model
{
    public class ValidationState : IValidationState
    {
        private Dictionary<string, ErrorTypes> _errors;
        private bool _isvalid;

        public ValidationState()
        {
            this._errors = new Dictionary<string, ErrorTypes>();
            this._isvalid = true;
        }

        public void AddError<TCommand>(Expression<Func<TCommand, object>> property, ErrorTypes errorType)
        {
            this._errors.Add(GetPropertyName(property), errorType);
            this._isvalid = false;
        }

        public void AddError(string key, ErrorTypes errorType)
        {
            this._errors.Add(key, errorType);
        }

        public bool ContainsKey<TCommand>(Expression<Func<TCommand, object>> property)
        {
            return this._errors.ContainsKey(GetPropertyName(property));
        }

        public bool ContainsKey(string key)
        {
            return this._errors.ContainsKey(key);
        }

        private static string GetPropertyName<T>(Expression<Func<T, object>> property)
        {
            string wholeType;
            string member;
            if (property.Body is UnaryExpression)
            {
                wholeType = typeof(T).ToString();
                member = ((UnaryExpression)property.Body).Operand.ToString().Split('.')[1];
            }
            else
            {
                wholeType = ((MemberExpression)property.Body).Member.DeclaringType.ToString();
                member = ((MemberExpression)property.Body).Member.Name;
            }

            string a = string.Format("{0}.{1}", wholeType, member);
            return a;
        }

        public bool IsValid
        {
            get { return this._isvalid; }
        }
    }
}